package com.tal.bcc.pad.cloud.upload;

import com.tal.bcc.pad.cloud.Log;
import com.tal.bcc.pad.cloud.coreprogress.ProgressHelper;
import com.tal.bcc.pad.cloud.coreprogress.ProgressListener;
import com.tal.bcc.pad.cloud.entity.CloudResult;
import com.tal.bcc.pad.cloud.listener.StsUploadListener;
import com.tal.bcc.pad.cloud.utils.CloudUtil;
import com.tal.bcc.pad.cloud.utils.DateUtils;
import com.tal.bcc.pad.cloud.utils.WebUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Dispatcher;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class XesUpload {
    private OkHttpClient okHttpClient;
    private ExecutorService executorService;


    public XesUpload() {

    }

    public void asyncUpload(CloudResult cloudResult, StsUploadListener progressCallBack) {
        HttpRequestParams httpRequestParams = new HttpRequestParams();
        Map<String, String> headers = new TreeMap();
        String date = DateUtils.getCurrentTimeByCalendar().trim();
        headers.put("host", cloudResult.getCloudOSSHost());
        headers.put("x-tss-date", date);
        List<String> canonicalRequest = this.assembleCanonicalRequest(cloudResult, headers);
        String auth = CloudUtil.getAuthorization(headers, canonicalRequest);
        httpRequestParams.addHeaderParam("Authorization", auth);
        Iterator var8 = headers.entrySet().iterator();

        while(var8.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry)var8.next();
            httpRequestParams.addHeaderParam((String)entry.getKey(), (String)entry.getValue());
        }

        httpRequestParams.addHeaderParam("accept", "application/json");
        httpRequestParams.addHeaderParam("Charset", "UTF-8");
        httpRequestParams.addHeaderParam("User-Agent", "okhttp/3.12.8");
        httpRequestParams.setContentType(cloudResult.getFileType());
        httpRequestParams.setWriteAndreadTimeOut(30);
        File file = new File(cloudResult.getUploadFilePath());
        if (file.exists() && file.length() != 0L) {
            httpRequestParams.addFileParam("file", file);
            this.upload2(cloudResult.getCloudFilePath(), httpRequestParams, cloudResult, progressCallBack);
        } else {
            cloudResult.setErrorCode("2");
            cloudResult.setErrorMsg("文件为空");
            progressCallBack.onError(cloudResult);
        }
    }

    private void upload2(String cloudFilePath, HttpRequestParams httpRequestParams, final CloudResult cloudResult, final StsUploadListener progressCallBack) {
        MediaType imageType = MediaType.parse(httpRequestParams.getContentType() + "; charset=utf-8");
        File file = (File)httpRequestParams.getFileParams().get("file");
        RequestBody body = RequestBody.create(imageType, file);
        RequestBody requestBody = ProgressHelper.withProgress(body, new ProgressListener() {
            public void onProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
                progressCallBack.onProgress(cloudResult, (int)(percent * 100.0F));
            }
        });
        Request.Builder requestBuilder = (new Request.Builder()).url(cloudFilePath).put(requestBody);
        if (httpRequestParams != null && httpRequestParams.getHeaderParams() != null) {
            Set<Map.Entry<String, String>> entries = httpRequestParams.getHeaderParams().entrySet();
            Iterator var11 = entries.iterator();

            while(var11.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry)var11.next();
                if (entry.getValue() != null) {
                    requestBuilder.addHeader((String)entry.getKey(), (String)entry.getValue());
                } else {
                    requestBuilder.addHeader((String)entry.getKey(), "");
                }
            }
        }

        this.okHttpClient = this.getOkHttpClient(httpRequestParams, false);
        Call call = this.okHttpClient.newCall(requestBuilder.build());
        call.enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                Log.e("TAG", e.getMessage());
                cloudResult.setErrorCode("2");
                cloudResult.setErrorMsg(e.getMessage());
                progressCallBack.onError(cloudResult);
            }

            public void onResponse(Call call, Response response) throws IOException {
                Log.e("TAG", "=============onResponse===============");
                progressCallBack.onSuccess(cloudResult);
            }
        });
    }

    private void upload(String url, HttpRequestParams httpRequestParams, final CloudResult cloudResult, final StsUploadListener progressCallBack) {
        try {
            MultipartBody.Builder builder = (new MultipartBody.Builder()).setType(MultipartBody.FORM);
            Iterator var7;
            Map.Entry entry;

            if (httpRequestParams != null && httpRequestParams.getBodyParams() != null) {
                Set<Map.Entry<String, String>> entries;
                entries = httpRequestParams.getBodyParams().entrySet();
                var7 = entries.iterator();

                while(var7.hasNext()) {
                    entry = (Map.Entry)var7.next();
                    if (entry.getValue() != null) {
                        builder.addFormDataPart((String)entry.getKey(), (String)entry.getValue());
                    } else {
                        builder.addFormDataPart((String)entry.getKey(), "");
                    }
                }
            }

            if (httpRequestParams != null && httpRequestParams.getFileParams() != null) {
                Set<Map.Entry<String, File>> entries;
                entries = httpRequestParams.getFileParams().entrySet();
                var7 = entries.iterator();

                while(var7.hasNext()) {
                    entry = (Map.Entry)var7.next();
                    if (entry.getValue() != null) {
                        builder.addFormDataPart((String)entry.getKey(), ((File)entry.getValue()).getName(), RequestBody.create(MediaType.parse(httpRequestParams.getContentType()), (File)entry.getValue()));
                    }
                }
            }

            MultipartBody formBody = builder.build();
            RequestBody requestBody = ProgressHelper.withProgress(formBody, null );
//            new ProgressUIListener() {
//                public void onUIProgressStart(long totalBytes) {
//                    super.onUIProgressStart(totalBytes);
//                    Log.e("TAG", "onUIProgressStart:" + totalBytes);
//                }
//
//                public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
//                    Log.e("TAG", "=============start===============");
//                    Log.e("TAG", "numBytes:" + numBytes);
//                    Log.e("TAG", "totalBytes:" + totalBytes);
//                    Log.e("TAG", "percent:" + percent);
//                    Log.e("TAG", "speed:" + speed);
//                    Log.e("TAG", "============= end ===============");
//                    progressCallBack.onProgress(cloudResult, (int)(percent * 100.0F));
//                }
//
//                public void onUIProgressFinish() {
//                    super.onUIProgressFinish();
//                    Log.e("TAG", "onUIProgressFinish:");
//                }
//            });
            Request.Builder requestBuilder = (new Request.Builder()).url(url).put(requestBody);
            if (httpRequestParams != null && httpRequestParams.getHeaderParams() != null) {
                Set<Map.Entry<String, String>> entries = httpRequestParams.getHeaderParams().entrySet();
                Iterator var10 = entries.iterator();

                while(var10.hasNext()) {
                    Map.Entry<String, String> item = (Map.Entry)var10.next();
                    if (item.getValue() != null) {
                        requestBuilder.addHeader((String)item.getKey(), (String)item.getValue());
                    } else {
                        requestBuilder.addHeader((String)item.getKey(), "");
                    }
                }
            }

            this.okHttpClient = this.getOkHttpClient(httpRequestParams, false);
            Call call = this.okHttpClient.newCall(requestBuilder.build());
            call.enqueue(new Callback() {
                public void onFailure(Call call, IOException e) {
                    Log.e("TAG", e.getMessage());
                    cloudResult.setErrorCode("2");
                    cloudResult.setErrorMsg(e.getMessage());
                    progressCallBack.onError(cloudResult);
                }

                public void onResponse(Call call, Response response) throws IOException {
                    Log.e("TAG", "=============onResponse===============");
                    progressCallBack.onSuccess(cloudResult);
                }
            });
        } catch (Exception var12) {
            Exception e = var12;
            cloudResult.setErrorCode("2");
            cloudResult.setErrorMsg(e.getMessage());
            progressCallBack.onError(cloudResult);
        }

    }

    private OkHttpClient getOkHttpClient(HttpRequestParams httpRequestParams, boolean retry) {
        if (this.okHttpClient == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder = builder.connectTimeout((long)httpRequestParams.getWriteAndreadTimeOut(), TimeUnit.SECONDS).readTimeout((long)httpRequestParams.getWriteAndreadTimeOut(), TimeUnit.SECONDS).writeTimeout((long)httpRequestParams.getWriteAndreadTimeOut(), TimeUnit.SECONDS).retryOnConnectionFailure(retry);
            builder.dispatcher(this.getDefaultDispatcher());
            builder.followRedirects(true);
            this.okHttpClient = builder.build();
        }

        return this.okHttpClient;
    }

    public synchronized Dispatcher getDefaultDispatcher() {
        Dispatcher dispatcher = new Dispatcher(this.executorService);
        this.executorService = dispatcher.executorService();
        return dispatcher;
    }

    public List<String> assembleCanonicalRequest(CloudResult cloudResult, Map<String, String> headers) {
        List<String> canonicalRequest = new ArrayList();
        canonicalRequest.add("PUT");
        canonicalRequest.add(cloudResult.getUploadFileUri());
        canonicalRequest.add("");
        canonicalRequest.add(WebUtils.buildCanonicalRequestHeaderQuery(headers));
        return canonicalRequest;
    }
}